export default {
    methods: {
        isAuthorize() {
            return new Promise((resolve, reject) => {
                wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success() {
                        resolve();
                    },
                    fail: () => {
                        this.requestAuth();
                    }
                });
            });
        },
        requestAuth() {
            wx.getSetting().then((res) => {
                if (!res.authSetting['scope.writePhotosAlbum']) {
                    wx.showModal({
                        title: '是否授权保存到相册',
                        content: '请确认授权，否则无法保存到相册',
                        success: (res) => {
                            if (res.confirm) {
                                wx.openSetting();
                            }
                        }
                    });
                }
            });
        },
        saveImage(imgSrc) {
            wx.downloadFile({
                url: imgSrc,
                success: function (res) {
                    wx.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success: function (data) {
                            uni.showToast({
                                title: '保存成功',
                                icon: 'success',
                                duration: 2000
                            });
                        },
                        fail: function (err) {
                            if (
                                err.errMsg !=
                                'saveImageToPhotosAlbum:fail cancel'
                            ) {
                                uni.showToast({
                                    icon: 'none',
                                    title: '保存失败，请稍后重试'
                                });
                            }
                        }
                    });
                },
                fail() {
                    uni.showToast({
                        icon: 'none',
                        title: '保存失败，请稍后重试'
                    });
                }
            });
        },
        saveImageToPhotosAlbum(fileUrl) {
            const imgSrc = this.$setImageUrl(fileUrl);

            this.isAuthorize().then(() => {
                this.saveImage(imgSrc);
            });
        }
    }
};
